package com.woniuxy.yoga.gateway.filter;


import com.woniuxy.yoga.commons.core.util.JWTUtil;
import com.woniuxy.yoga.commons.redis.util.RedisUtil;
import com.woniuxy.yoga.gateway.config.AuthenUrlProperties;
import com.woniuxy.yoga.gateway.exception.AuthenException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

@Component
@Order(2)
public class BusinessLoginAuthenFilter implements GlobalFilter {

    @Autowired
    private AuthenUrlProperties aup;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().toString();
        //判断是否是公共的放行的url
        if (AdminLoginAuthenFilter.match(aup,url)) {
            return chain.filter(exchange);
        }
        if(aup.matchAdmin(url)||aup.matchCoach(url)||aup.matchBusiness(url)||aup.matchUser(url)){
            return chain.filter(exchange);
        }
        //判断是否是商家端请求
        int index = url.lastIndexOf(".");
        if (index==-1) {
            return chain.filter(exchange);
        }else if(!(url.substring(index).equals(".bu"))){
            return chain.filter(exchange);
        }
        //认证
        System.out.println("---------开始认证商家端登录状态--------------");
        List<String> tokens = exchange.getRequest().getHeaders().get("authen_token");
        if (tokens==null||tokens.size()<=0) {
            throw new AuthenException(401,"未登录");
        }
        String businessToken = tokens.get(0);
        try {
            JWTUtil.parseBusinessToken(businessToken);
        } catch (Exception e) {
            e.printStackTrace();
            //短token过期
            //获取长token
            String refreshToken = redisUtil.get(businessToken);
            if (refreshToken==null) {
                //长token过期
                throw e;
            }else {
                //长token未过期 重新签发短token
                Claims claims = JWTUtil.parseBusinessToken(refreshToken);//如果jwt本身过期 也会抛出异常
                Object businessId = claims.get("businessId");
                Object businessName = claims.get("businessName");
                HashMap<String, Object> map = new HashMap<>();
                map.put("businessId",businessId);
                map.put("businessName",businessName);
                businessToken = JWTUtil.createBusinessToken(map, 30);//短token有效时间30分钟
                //使用短token为键 长token为值存储到redis中
                redisUtil.set(businessToken,refreshToken,3*24*60*60L);//长token在redis中的有效期为三天，这里设置的时间不影响长token的有效时间
                //重新签发短token
                //暴露自定义响应头给前端
                ServerHttpResponse serverHttpResponse = exchange.getResponse();
                serverHttpResponse.getHeaders().set("authen_token",businessToken);
                serverHttpResponse.getHeaders().set("Access-Control-Expose-Headers","authen_token");
                ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().header("authen_token", businessToken).build();
                ServerWebExchange webExchange = exchange.mutate().request(serverHttpRequest).response(serverHttpResponse).build();
                return chain.filter(webExchange);
            }
        }
        return chain.filter(exchange);
    }
}
